<?php

class WishModel extends BaseModel
{
    var $table  = 'wish';
    var $prikey = 'id';
    var $_name  = 'wish';
    var $_relation  = array(
        'has_member' => array(
            'model'         => 'member',
            'type'          => BELONGS_TO,
            'foreign_key'   => 'user_id',
            'reverse' => 'user_question',
        ),
        'has_goods' => array(
            'model'         => 'goods',
            'type'          => BELONGS_TO,
            'foreign_key'   => 'goods_id',
            'reverse'       => 'be_wish',
        ),
        'has_goods_spec' => array(
            'model'         => 'goodsspec',
            'type'          => BELONGS_TO,
            'foreign_key'   => 'spec_id',
            'reverse'       => 'spec_wish',
        ),
    );

    function createOrder($id){

        $orderModel = &m('order');
        $memberModel = &m('member');
        $wishPayLog = &m('wish_pay_log');
        $orderExtm = &m('orderextm');
        $goods = &m('goods');
        $store = &m('store');
        $orderGoods = &m('ordergoods');
        $goodsspec = &m('goodsspec');

        $info = $this->get(array(
            'conditions'  =>  'id = '.$id
        ));

        $conditions = 'wish.spec_id = '.$info['spec_id'];
        $conditions .= ' AND wish.id = '.$id;

        //查询匹配的规格信息
        $goodsSpecInfo = $this->get(array(
            'fields'  => 'gs.*',
            'join'     =>  'has_goods_spec',
            'conditions'    =>  $conditions,
            'count' => true,
        ));
        //判断当前心愿单数量和当前库存数不足时 将此规格的心愿单全部失效并退款
        if($info['num'] > $goodsSpecInfo['stock']){
            //查看当前规格的库存数是否满足所有此规格的心愿单
            $where = 'spec_id = '.$info['spec_id'] .' AND state = 1';
            $wishList = $this->find(array(
                'conditions'    =>  $where,
            ));

            //遍历所有符合条件的心愿单进行比较库存，库存不满足的心愿单失效并退款
            $saveData['state'] = 3;
            $wishIds = '';


            foreach($wishList as $item){
                if($item['num'] < $goodsSpecInfo['stock']){
                    $this->edit($item['id'],$saveData);
                    //查询每笔心愿单的每笔交易记录   并进行退款
                    $wishInfo = $wishPayLog->find(array('conditions'=>'wish_id = '.$item['wish_id']));
                    foreach($wishInfo as $k=>$value){
                        $info['order_sn'] = $value['trade_no'];
                        $newArr['total_fee'] = $value['money'];
                        $info['payment_code'] = 'alipay_app';
                        $newArr['refund_sn'] = $value['order_sn'];
                        if($value['pay_type'] == 1){
                            $info['payment_code'] = 'wxpay_app';
                        }
                        $resultWishReturn = $this->refundSign($newArr,$info);
                    }
                    $wishIds .= ','.$item['id'];
                }
            }
            $wishIds = explode(',',$wishIds);
            return array('code'=>9999,'msg'=>'库存不足，已经退款','data'=>$wishIds);
            exit;
        }

        $data['finish_time'] = time();
        $data['state'] = 2;
        $res = $this->edit($id,$data);
        if($res){

            //当前心愿单用户信息
            $memberInfo = $memberModel->get(array('conditions'=>"user_id =".$info['user_id']));

            //当前心愿单支付信息
            $wishPayLogInfo = $wishPayLog->get(array('conditions'=>'wish_id = '.$id));
            //确定支付方式  1微信 2支付宝
            if($wishPayLogInfo['pay_type'] == 1){
                $payment_id = 1;
                $payment_name = '手机微信支付';
                $payment_code = 'wxpay_app';
            }elseif($wishPayLogInfo['pay_type'] == 2){
                $payment_id = 2;
                $payment_name = '手机支付宝支付';
                $payment_code = 'alipay_app';
            }
            if($goodsSpecInfo['stock'] < 1){
                return array('code'=>-1,'msg'=>'库存不足');
            }

            //减去规格中的库存
//            $stock = $goodsSpecInfo['stock'] - $info['num'];
//            $saveave['stock'] = $stock;
//            $goodsspecSaveStock = $goodsspec->edit($info['spec_id'],$saveave);
//            if(!$goodsspecSaveStock){
//                return array('code'=>-1,'msg'=>'库存修改失败');
//            }

            //查询商品详细信息
            $goodsInfo = $goods->get_info($info['goods_id']);
            //查询商家信息
            $storeInfo = $store->get_info($goodsInfo['store_id']);

            $goodsPrice = $wishPayLog->getPayLog($id,1) + $wishPayLog->getPayLog($id,2);

            //组合订单信息
            $arr = array(
                'order_sn'          => $this->_gen_order_sn(),
                'type'              => 'wishOrder',
                'extension'         => 'wish_normal',
                'seller_id'         => $goodsInfo['store_id'],
                'seller_name'       => $storeInfo['store_name'],
                'buyer_id'          => $info['user_id'],
                'buyer_name'          => $memberInfo['user_name'],
                'buyer_no'          => $memberInfo['user_no'],
                'phone_mob'          => $memberInfo['phone_mob'],
                'buyer_email'          => $memberInfo['email'],
                'add_time'          => time(),
                'status'            => 20,      //已支付状态
                'payment_id'        => $payment_id,      //支付方式id
                'payment_name'      => $payment_name,      //支付名称
                'payment_code'      => $payment_code,      //支付编码
                'out_trade_sn'      => $wishPayLogInfo['trade_no'],      //支付订单号
                'pay_time'          => $wishPayLogInfo['create_time'],      //支付时间
                'goods_amount'      => $info['goods_price'],      //合计金额
                'order_amount'      => $goodsPrice,      //实际付款金额
            );

            $addOrderInfo = $orderModel->add($arr);
            if (!$addOrderInfo) {
                return array('code'=>-1,'msg'=>'生成订单失败');
            }
            //验证收货人地址信息
            $resAddress = $this->_valid_consignee_info($info['addr_id']);
            /* 插入收货人信息 */
            $resAddress['order_id'] = $addOrderInfo;

            $resOrderExtm = $orderExtm->add($resAddress);



            $goods_items = array(
                'order_id' => $addOrderInfo,
                'goods_id' => $goodsInfo['goods_id'],
                'goods_name' => $goodsInfo['goods_name'],
                'spec_id' => $info['spec_id'],
                'specification' => $goodsInfo['spec_name_1'].':'.$goodsSpecInfo['spec_1value'].' '.$goodsInfo['spec_name_2'].':'. $goodsSpecInfo['spec_2'],
                'price' => $goodsPrice,
                'quantity' => $info['num'],
                'goods_image' => $goodsSpecInfo['spec_1'],
                'goods_old_price' => $info['goods_price'],
                'price_amount' => $goodsPrice,
                'tax_price_amount' => round($goodsInfo['tax_price'] * $info['num'],2),
                'price_total' => $goodsPrice,
                'goods_type' => $goodsInfo['goods_type'] ? $goodsInfo['goods_type'] : 1,
                'promotions_id' => $goodsInfo['promotions_id'] ? $goodsInfo['promotions_id'] : 0,
            );
            $addOrderGoods = $orderGoods->add($goods_items);

            //新增加入订单log信息
            $order_log_array = array(
                'order_id' => $addOrderInfo,
                'operator' => $memberInfo['user_name'],
                'order_status' => '',
                'changed_status' => '支付订单',
                'remark' => '顾客完成支付,平台正在处理订单',
                'log_time' => time(),
                'operator_type' => 'buyer',
                'status' => 1,
                'customs_status' => 20,
            );
            $logInfo = &m('orderlog')->add($order_log_array);


            $this->edit($id,array('order_id'=>$addOrderInfo));


            if($addOrderGoods){
                //推送oms订单
                $this->omsIndex($addOrderInfo);
                return array('code'=>1,'msg'=>'success');
            }
            return array('code'=>-1,'msg'=>'生成订单信息错误');
        }
        return array('code'=>-1,'msg'=>'网络错误');
    }


    function omsIndex($res_order)
    {
        ini_set('error_log', ROOT_PATH . '/temp/logs/wish_to_oms' . date('y_m_d') . '.log');

        $message = print_r('-------------收到订单id：'.$res_order, true);
        $this->writeLog('心愿单开始：' . $message);

        /* 获取订单明细信息 */
        $model_order = & m('order');
        $model_member = & m('member');
        $coupon_mod = & m('couponsn');
        $goods_mod = & m('goods');
        $member_mod = & m('member');
//            lichen 2019/4/24 start
        $goods_spec_mod = & m('goodsspec');
        $storestock_mod = & m('storestock');
        $tax_mod = & m('my_tax');
        $unit_mod = & m('unit');
        $order_goods_mod =  & m('ordergoods');
        $order_extm_mod = & m('orderextm');
        $country_mod = & m('country_info');
        $wrap_mod = & m('wrap');
        $wishModel = &m('wish');
//            lichen 2019/4/24 end
        $order_id = $res_order;
        $order_info = $model_order->get($order_id);
        $order_goods = $order_goods_mod->find(array(
            'conditions' => "order_id=".$res_order,
        ));
        $order_extm = $order_extm_mod->get('order_id='.$order_id);
        $member = $member_mod->get('user_id=' . $order_info['buyer_id']);
        $wish = $wishModel->get('order_id = '.$order_id);
        $send_data = $order_info;
        $send_data['order_goods'] = $order_goods;
        $send_data['order_extm'] = $order_extm;
        $send_data['member'] = $member;
        $send_data['wish'] = $wish;

        $this->writeLog('心愿单开始：数据格式1' . json_encode($send_data));

        foreach ($send_data['order_goods'] as $k=>$v){
            $temp_goods_spec = $goods_spec_mod->get('spec_id='.$send_data['order_goods'][$k]['spec_id']);
            $temp_goods = $goods_mod->get('goods_id='.$send_data['order_goods'][$k]['goods_id']);
//                var_dump($temp_goods);exit;
            $temp_storestock = $storestock_mod->get('storestock_id='.$temp_goods_spec['spec_3value']);
            $temp_tax = $tax_mod->get('tax_id='.$temp_goods['tax_id']);
            $temp_unit = $unit_mod->get('id='.$temp_goods['unit_id']);
            $temp_country = $country_mod->get('id='.$temp_goods['country_id']);
            $temp_wrap= $wrap_mod->get('id='.$temp_goods['wrap_id']);
            $send_data['order_goods'][$k]['spec'] = $temp_goods_spec;
            $send_data['order_goods'][$k]['goods'] = $temp_goods;
            $send_data['order_goods'][$k]['storestock'] = $temp_storestock;
            $send_data['order_goods'][$k]['tax'] = $temp_tax;
            $send_data['order_goods'][$k]['unit'] = $temp_unit;
            $send_data['order_goods'][$k]['country'] = $temp_country;
            $send_data['order_goods'][$k]['wrap'] = $temp_wrap;

        }
        $this->writeLog('心愿单开始：数据格式2' . json_encode($send_data));

        $sen_data = $this->_get_oms_data($send_data);
        $this->writeLog('心愿单开始：组合发送oms数据' . json_encode($sen_data));

        $res_wish = & m('wish')->get( 'order_id = '.$order_id);
        $res_pay = & m('wish_pay_log')->find(array(
                'conditions' => 'wish_id = '.$res_wish['id'],
            )
        );

        $message = print_r('付款数据格式：'.$res_pay, true);
        error_log('心愿单开始：' . $message);
        $temp_pay = $this->_get_pay_data($order_info['order_sn'],$res_pay);
        $sen_data['OrderPayments'] = $temp_pay;
        $message = print_r($sen_data, true);
        error_log('心愿单OMS数据为：' . $message);
//            lichen 2019/4/22 start
        $url = OMS_WISH_URL; #url 地址必须 http://xxxxx
        $port = OMS_PORT;
        $message = print_r($url, true);
        error_log('心愿单OMS路径为：' . $message);
        $t=10;
        $asdasd = $this->_post_to_oms($url,$sen_data);
        $message = print_r('-------------', true);
        error_log('返回结果：' . json_encode($asdasd));
        error_log('心愿单结束：' . $message);
    }


    function _get_oms_data($data = array()){
        $return_array['OrderItets'] = array();
        foreach ($data['order_goods'] as $k => $v) {
            if(!array_key_exists($data['order_goods'][$k]['goods']['goods_id'],$return_array['OrderItets'])){
                $return_array['OrderItets'][$v['goods_id']]['ProductId'] = $data['order_goods'][$k]['goods']['goods_id'];
                $return_array['OrderItets'][$v['goods_id']]['ItemName'] = '爱莎';
                $return_array['OrderItets'][$v['goods_id']]['Unit'] = $data['order_goods'][$k]['unit']['unit_code'];
                $return_array['OrderItets'][$v['goods_id']]['Currency'] = '142';
                $return_array['OrderItets'][$v['goods_id']]['CiqCurrency'] = '156';
                $return_array['OrderItets'][$v['goods_id']]['Country'] = $data['order_goods'][$k]['country']['country_code'];
                $return_array['OrderItets'][$v['goods_id']]['CiqCountry'] = $data['order_goods'][$k]['country']['ciq_code'];
                $return_array['OrderItets'][$v['goods_id']]['WrapTypeCode'] = $data['order_goods'][$k]['wrap']['wrap_code'];
                //                test
                $return_array['OrderItets'][$v['goods_id']]['PurposeCode'] = '9';
                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = $data['seller_id'];
                $return_array['OrderItets'][$v['goods_id']]['StoreId'] = $data['seller_id'];
//                $return_array['OrderItets'][$v['goods_id']]['VendorId'] = 16;

                $return_array['OrderItets'][$v['goods_id']]['ShelfGoodsName'] = $data['order_goods'][$k]['goods']['brand'];

                $return_array['OrderItets'][$v['goods_id']]['ProductSku'] = 'none';
                $return_array['OrderItets'][$v['goods_id']]['BarCode'] = 'none';


            }
            $return_array['OrderItets'][$v['goods_id']]['OrderItemDetails'][] = array(
                'AttributeSku' => $data['order_goods'][$k]['spec']['sku'],
                'Quantity' => $data['order_goods'][$k]['quantity'],
                'Price' => $data['order_goods'][$k]['spec']['price'],
                'TaxRates' => $data['order_goods'][$k]['tax']['consolidated_tax'],
                'OrderTax' => $data['order_goods'][$k]['tax_price'],
                'OrderDiscount' => 0,
                'BarCode' => $data['order_goods'][$k]['spec']['barcode'],
                'TradeType' => $data['order_goods'][$k]['storestock']['stock_style'],
                'PriceInclTax' => $data['order_goods'][$k]['goods']['price'],
                'TotalPrice' => $data['order_goods'][$k]['price_total'],
                'WarehouseId' =>  $data['order_goods'][$k]['storestock']['stock_id'],
            );

        }
        $address_str = $this->emptyreplace($data['order_extm']['region_name']);
        $address_str = $address_str . $data['order_extm']['address'];

        $return_array['OtherNo'] = date("YmdHis",$data['wish']['add_time']).$data['wish']['id'];
        $return_array['LockInInventory'] = 20;
        $return_array['OrderStatusId'] = 10;
        $return_array['ShippingStatusId'] = 20;
        $return_array['PaymentStatusId'] = 30;
        $return_array['PaymentMethodSystemName'] = 'none';
        $return_array['ShippingMethod'] = 'ground';
        $return_array['CustomerCurrencyCode'] = '142';
        $return_array['AuthorizationTransactionResult'] = 'none';
        $return_array['OrderTotal'] = $data['goods_amount'];
        $return_array['AffiliateId'] = 0;
        $return_array['RefundedAmount'] = 0;
        $return_array['CreatedOnUtc'] = date("Y-m-d H:i:s");
        $return_array['OrderNo'] = $data['order_sn'];
        $return_array['BuyerName'] = $data['member']['real_name'];
        $return_array['BuyerTelephone'] = $data['phone_mob'];
        $return_array['BuyerRegNo'] = $data['phone_mob'];
        $return_array['BuyerIdType'] = 1;
        $return_array['BuyerIdNumber'] = $data['member']['user_no'];
        $return_array['PayCode'] = 'none';
        $return_array['PayName'] = 'none';
        $return_array['PayTransactionId'] = 'none';
        $return_array['Consignee'] = $data['order_extm']['consignee'];
        $return_array['ConsigneeTelephone'] = $data['order_extm']['phone_mob'];
        $return_array['ConsigneeAddress'] = $address_str;
        $return_array['IdCard'] = $data['order_extm']['user_no'];
        $return_array['IdType'] = 1;
        $return_array['EtradeCountryCode'] = '156';
        $return_array['OrderPayments'] = array();
        $return_array['OrderItems'] = array();
        $return_array['OrderItems'] = array_values($return_array['OrderItets']);
        unset($return_array['OrderItets']);
        return $return_array;

    }

    function _get_pay_data($order_sn,$data){
        $return_array = array();
        foreach ($data as $k => $v){
            $return_array[] = array(
                'PayName' => $v['pay_type'] == 1 ? '财付通支付科技有限公司' : '支付宝(中国)网络技术有限公司',
                'OrderNo' => $order_sn,
                'WishNo' => $v['order_sn'],
                'PayTransactionId' => $v['trade_no'],
                'PayPrice' => $v['money'],
                'PayTime' => date("Y-m-d H:i:s",$v['create_time'])
            );
        }
        return $return_array;
    }

    function _post_to_oms($url,$data)
    {
        $data_string = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        //https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        $res = curl_exec($ch);
        if (!$res) {
            return false;
        } else {
//            return true;
            return json_decode($res,true);
        }
    }

    function emptyreplace($str)
    {
        $str = preg_replace('/\s+/',',',$str);
        return $str;
    }




    /**
     *    生成订单号
     *
     *    @author    Garbin
     *    @return    string
     */
    function _gen_order_sn() {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        $timestamp = time();
        $y = date('y', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        $orders = &m('order')->get(array('conditions'=>'order_sn = '.$order_sn));
        if (empty($orders['order_sn'])) {
            /* 否则就使用这个订单号 */
            return $order_sn;
        }

        /* 如果有重复的，则重新生成 */
        return $this->_gen_order_sn();
    }

    /**
     *    验证收货人信息是否合法
     *
     *    @author    Garbin
     *    @param     array $consignee
     *    @return    void
     */
    function _valid_consignee_info($addr_id) {
        if (!$addr_id) {
            $this->show_warning('收货地址为空');
            return;
        }
        //通过address_id  获取收货信息,存储到订单拓展表
        $address = &m('address')->get(array('conditions'=>'addr_id = '.$addr_id));
        if(empty($address)){
            $this->show_warning('下订单收货地址不存在');
            return;
        }
        $consignee['consignee'] = $address['consignee'];
        $consignee['region_id'] = $address['region_id'];
        $consignee['region_name'] = $address['region_name'];
        $consignee['user_no'] = $address['user_no'];
        $consignee['address'] = $address['address'];
        $consignee['zipcode'] = $address['zipcode'];
        $consignee['phone_mob'] = $address['phone_mob'];
        $consignee['shipping_fee'] = 0;
        $consignee['shipping_id'] = 0;
        $consignee['shipping_name'] = '商家包邮';

        return $consignee;
    }
    //对三方支付进行退款封装
    function refundSign($refund,$order_info){

        ini_set('display_errors','on');
        error_reporting(E_ALL);

        $out_trade_no = $order_info["order_sn"];
        $total_fee = $refund["total_fee"] * 100;
        $refund_fee = $refund["total_fee"] * 100;
        $refund_alifee = $refund["total_fee"];
        if($order_info['payment_code'] == 'epaywxnative' || $order_info['payment_code'] == 'wxpay_app'){
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Data.php";
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Api.php";
            include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Config.php";
            $input = new WxPayRefund();
            $input->SetOut_trade_no($out_trade_no);
            $input->SetTotal_fee($total_fee);
            $input->SetRefund_fee($refund_fee);
            $config = new WxPay1Config();
            $input->SetOut_refund_no($refund['refund_sn']);
            $rs = WxPay1Api::refund($config,$input, 60);
            if($rs['return_code'] != 'SUCCESS'){
                return false;
            }
        }else if($order_info['payment_code'] == 'epayalipay' || $order_info['payment_code'] == 'alipay_app'){
            $config = include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/config.php";
            include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
            include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
            //商户订单号，商户网站订单系统中唯一订单号
            $out_trade_no = trim($out_trade_no);
            //需要退款的金额，该金额不能大于订单金额，必填
            $refund_amount = trim($refund_alifee);
            //构造参数
            $RequestBuilder=new AlipayTradeRefundContentBuilder();
            $RequestBuilder->setOutTradeNo($out_trade_no);
            $RequestBuilder->setRefundAmount($refund_amount);
            $aop = new AlipayTradeService($config,true);

            $response = $aop->Refund($RequestBuilder);
            $rs = json_decode(json_encode($response,true));
            if($rs['alipay_trade_refund_response']['code'] != '10000'){
                return true;
            }else{
                return false;
            }
        }
    }

    function writeLog($mes)
    {
        $years = date('Y-m-d');
        //设置路径目录信息
        $url  = '../temp/logs/'.$years.'/'.$years.'_request_log.txt';
        //取出目录路径中目录(不包括后面的文件)
        $dir_name = dirname($url);
        //如果目录不存在就创建
        if(!file_exists($dir_name)) {
            $res = mkdir(iconv("UTF-8","GBK",$dir_name),0777,true);
        }
        file_put_contents($url,date('Y-m-d H:i:s').":".$mes."\n",FILE_APPEND);
    }
}

?>
